package com.ph.shopping.facade.pay.service.impl;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.ph.shopping.common.core.base.BaseService;
import com.ph.shopping.common.core.constant.SmsCodeConstant;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.core.customenum.SmsCodeType;
import com.ph.shopping.common.core.exception.BizException;
import com.ph.shopping.common.util.com.order.CreateOrderUtil;
import com.ph.shopping.common.util.com.order.OrderBizCode;
import com.ph.shopping.common.util.date.ThreadLocalDateUtil;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.common.util.rsa.MD5;
import com.ph.shopping.facade.mapper.MemberDrawcashRecordMapper;
import com.ph.shopping.facade.pay.bean.BodyInfo;
import com.ph.shopping.facade.pay.constant.PayConstant;
import com.ph.shopping.facade.pay.entity.MemberDrawcashRecord;
import com.ph.shopping.facade.pay.enums.CashPayStatusEnum;
import com.ph.shopping.facade.pay.service.ICashService;
import com.ph.shopping.facade.pay.service.gzylcash.GZYLCashService;
import com.ph.shopping.facade.pay.utils.UniqueUtils;
import com.ph.shopping.facade.pay.vo.CashVo;
import com.ph.shopping.facade.pay.vo.CertificatesAuthVo;
import com.ph.shopping.facade.pay.vo.MemberByCashVo;
import com.ph.shopping.facade.pay.vo.SmsCodeVo;

/**
 * @项目：phshopping-facade-member
 *
 * @描述：会员提现service
 *
 * @作者： Mr.chang
 *
 * @创建时间：2017年4月6日
 *
 * @Copyright @2017 by Mr.chang
 */
@Component
@Service(version="1.0.0")
public class CashService extends BaseService implements ICashService{
	
	private static final Logger log = LoggerFactory.getLogger(CashService.class);
	
	@Autowired
	private MemberDrawcashRecordMapper memberDrawcashRecordMapper;
	
	@Autowired
	private GZYLCashService gzylashServiceImpl;

	@Transactional(rollbackFor=Exception.class)
	@Override
	public Result addMemberCashOrder(CashVo mi,String requestIP) throws BizException {
		log.info("开始执行会员提现流程...............");
		log.info("会员提现流程参数："+JSON.toJSONString(mi));
		
		MemberByCashVo mch=memberDrawcashRecordMapper.getMemberInfo(mi.getId());
		//验证会员是否绑定身份证
		if(StringUtils.isEmpty(mch.getIdCard())){
			return getResult(ResultEnum.ID_IS_EMPTY);
		}
		//判断是否绑定银行卡
		if (StringUtils.isEmpty(mch.getBankCard())) {
			return getResult(ResultEnum.NO_CHECKBIND_EXCEPTION);
		}
		//判断是否设置支付密码
		if(org.springframework.util.StringUtils.isEmpty(mch.getPayPwd())){
			return getResult(ResultEnum.PAY_PWD_EMPTY);
		}
		//查询是否已进行实名认证
		CertificatesAuthVo ca=memberDrawcashRecordMapper.getCretificateAuthInfo(mch.getIdCard());
		if(StringUtils.isEmpty(ca)){
			return getResult(ResultEnum.ID_NOT_CERTIFIED);
		}
		long cashScore=mi.getCashScore()*10000l;
		//判断提现积分是否大于可用积分
		if(cashScore>mch.getEnableScore().longValue()){
			return getResult(ResultEnum.CASH_MONEY_PASS_ENABLE_ERROR);
		}
		//判断当前提现积分是否大于单笔最小金额以及提现积分是否小于单笔最大金额
		if(mi.getCashScore().longValue()*10000<PayConstant.MIN_CASH_MONEY||mi.getCashScore()*10000>PayConstant.MAX_CASH_MONEY){
			return getResult(ResultEnum.CASH_MONEY_PASS_MAX_ERROR);
		}
		//查询改用户当天提现的积分总和
		Long cashedScore=memberDrawcashRecordMapper.getSumScoreThisDay(mi.getId());
		if(cashedScore.longValue()>PayConstant.MAX_CASH_MONEY_EVERY_DAY){
			return getResult(ResultEnum.CASH_MONEY_PASS_MAX_ERROR);
		}
		//判断验证码是否存在
		SmsCodeVo scv=memberDrawcashRecordMapper.getSmsCodeByPhone(mch.getPhone(),SmsCodeType.MEMBER_CASH.getCodeType());
		if (StringUtils.isEmpty(scv)) {
			return getResult(ResultEnum.SMS_CODE_EMPTY);
		}
		//验证码是否过期
		if (ThreadLocalDateUtil.dateDifferSeconds(scv.getCreateTime())>SmsCodeConstant.SMS_EFFECTIVE_TIME) {
			return getResult(ResultEnum.SMS_CODE_INVALID);
		}
		//判断验证码是否正确
		if (!mi.getMsgCode().equals(scv.getSmsCode())) {
			return getResult(ResultEnum.SMS_CODE_ERROR);
		}
		//判断支付密码是否正确
		if (!MD5.getMD5Str(mi.getPayPwd().trim()).equals(mch.getPayPwd())) {
			return getResult(ResultEnum.PAY__PWD_ERROR);
		}
		
		Result result=getResult(ResultEnum.SUCCESS);
		try {
			//生成代付交易批次号
			String batchNo=UniqueUtils.getBathNo();
			//新增提现记录
			MemberDrawcashRecord mdr=new MemberDrawcashRecord();
			mdr.setMemberId(mi.getId());
			mdr.setAmount(cashScore-PayConstant.HANDING_CHARGE);
			mdr.setHandingCharge(PayConstant.HANDING_CHARGE);
			mdr.setOrderNum(CreateOrderUtil.createOrderCode(OrderBizCode.MEMBER_DRAW_CASH));
			mdr.setAccountName(mch.getRealName());
			mdr.setBankCardNo(mch.getBankCard());
			mdr.setRequestIp(requestIP);
			mdr.setBatchNo(batchNo);
			mdr.setStatus(CashPayStatusEnum.PAY_CASHING.getCode());
			mdr.setCreater(mi.getId());
			mdr.setCreateTime(new Date());
			memberDrawcashRecordMapper.insertUseGeneratedKeys(mdr);
			log.error("新增返回的主键id:"+mdr.getId());
			//调用代付接口 TODO
//			BodyInfo bi=new BodyInfo(mdr.getId().toString(), mdr.getOrderNum(), "6222033100000756083", "田云", mdr.getAmount().toString(), "", mdr.getOrderNum(), mdr.getOrderNum());//提现测试环境
			BodyInfo bi=new BodyInfo(mdr.getId().toString(), mdr.getOrderNum(), mch.getBankCard(), mch.getRealName(), mdr.getAmount().toString(), "", mdr.getOrderNum(), mdr.getOrderNum());//提现正式环境
			gzylashServiceImpl.defrayPay(bi,"");
			result=getResult(ResultEnum.SUCCESS);
		} catch (Exception e) {
			log.error("会员提现异常："+e);
			result=getResult(ResultEnum.CASH_MEMBER_EXCEPTION);
			throw new BizException(ResultEnum.CASH_MEMBER_EXCEPTION.getMsg(),Integer.parseInt(ResultEnum.CASH_MEMBER_EXCEPTION.getCode()));
		}
		log.info("结束执行会员提现流程...............");
		return result;
	}

}
